<template>
  <div>
    <!-- 编辑楼栋信息的对话框 -->
    <el-form ref="editedUnitForm" :model="editedUnitForm" :rules="rules" label-width="80px">

      <el-form-item label="楼栋" prop="buildingId">
        <el-select v-model="editedUnitForm.buildingId" placeholder="请选择">
          <el-option v-for="item in buildingName" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="单元名称" prop="unitCode">
        <el-input v-model="editedUnitForm.unitCode"></el-input>
      </el-form-item>

      <el-form-item label="楼层" prop="floor">
        <el-input v-model="editedUnitForm.floor"></el-input>
      </el-form-item>

      <el-form-item label="单元物品" prop="publicProperty">
        <el-select v-model="editedUnitForm.publicProperty" multiple placeholder="请选择">
          <el-option v-for="item in publicProperty" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveEditedUnitForm">确 定</el-button>
      <el-button type="info" @click="cancellation">取 消</el-button>
    </div>
  </div>
</template>


<script>
export default {
  props: {
    message: {
      type: String,
      default: 'Default Message' // 设置 message 的默认值为 'Default Message'
    }
  },
  data() {
    return {
      editedUnitForm: {
        unitId: '',
        buildingId: '',
        buildingName: '',
        unitCode: '',
        floor: '',
        publicProperty: '',
      },
      publicProperty: [
        {
          value: "洗衣机",
          label: "洗衣机"
        },
        {
          value: "吹风机",
          label: "吹风机"
        },
        {
          value: "洗鞋机",
          label: "洗鞋机"
        },
      ],
      buildingName: [],//楼栋集合
      rules: {
        buildingId: [{required: true, message: '请选择楼栋', trigger: 'blur'}],
        // buildingName: [{ required: true, message: '请输入楼栋名称', trigger: 'blur' }],
        unitCode: [{required: true, message: '请输入单元名称', trigger: 'change'}],
        floor: [{required: true, message: '请输入楼层', trigger: 'blur'}],
        // publicProperty: [{ required: true, message: '请选择单元物品', trigger: 'blur' }]
      }
    };
  },
  watch: {
    // 监听 message 属性的变化
    message(newValue, oldValue) {
      this.getUnitById(newValue);
    },
  },
  mounted() {
    // 组件挂载后立即获取数据
    this.getUnitById(this.message);
    //   查询楼栋信息
    this.queryBuildingInformation();
  },
  methods: {
    // 查询楼栋信息
    queryBuildingInformation() {
      // 调用后端接口获取数据
      this.$axios.post('/api/buildings/list', {}, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {
          // 使用 reduce 构建以 userId 为键，name 为值的对象
          this.buildingName = response.data.data.reduce((arr, building) => {
            // 将当前用户的 userId 作为键，name 作为值，添加到累积的数组中
            arr.push({value: building.buildingId, label: building.buildingName});
            return arr;
          }, []);
        } else {
          this.$message.error(response.data.msg || '查询楼栋信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '查询楼栋信息失败');

      });
    },
    // 提交修改
    saveEditedUnitForm() {
      this.$refs.editedUnitForm.validate(valid => {
        if (valid) {
          // 构建楼栋信息对象
          const requestBody = {
            unitId: this.editedUnitForm.unitId,
            buildingId: this.editedUnitForm.buildingId,
            unitCode: this.editedUnitForm.unitCode,
            floor: this.editedUnitForm.floor,
            publicProperty: this.editedUnitForm.publicProperty.join(',')

          };
          // 发送 put 请求
          this.$axios.put('/api/units/update', requestBody, {
            headers: {
              'token': this.$store.getters.getToken
            }
          })
              .then(response => {
                // 自定义一个事件，使其能够修改成功之后自动隐藏！
                this.$emit('unitsUpdate');
                // 处理登录成功的情况，比如保存用户信息到本地存储或者跳转到其他页面
                if (response.data.code === 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                } else {
                  this.$message.error(response.data.msg || '修改单元失败');
                }
              })
              .catch(error => {
                // 自定义一个事件，使其能够添加成功之后自动隐藏！
                this.$emit('unitsUpdate');
                // 处理错误情况
                this.$message({
                  message: '修改失败',
                  type: 'error'
                });
              });
        } else {
          return false;
        }
      });
    },

    // 取消按钮
    cancellation() {
      this.$emit('unitsUpdate');
    },

    // 根据ID查询按钮
    getUnitById(id) {
      // 发送 POST 请求获取单元列表
      this.$axios.get('/api/units/' + id, {
        headers: {
          'token': this.$store.getters.getToken
        }
      })
          .then(response => {
            // 请求成功，从响应中提取出需要的数据
            const data = response.data;
            if (data.code === 200) {
              this.editedUnitForm = response.data.data;
              // 使用 split() 方法将字符串转换成数组
              this.editedUnitForm.publicProperty = response.data.data.publicProperty.split(',');
            } else {
              this.$message.error(response.data.msg || '获取单元信息失败');
            }
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
  },
  computed: {}
};
</script>
